package com.solcoo.merchant.ui.setting;

import java.io.File;
import java.util.HashMap;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.solcoo.common.App;
import com.solcoo.common.image.BitmapHelper;
import com.solcoo.common.image.ImageLoader;
import com.solcoo.common.image.activity.CameraActivity;
import com.solcoo.common.image.activity.CropActivity;
import com.solcoo.common.image.convertor.RoundedCornerConvertor;
import com.solcoo.common.util.FileUtil;
import com.solcoo.common.view.BottomDialog;
import com.solcoo.merchant.ApplicationExt;
import com.solcoo.merchant.Constant;
import com.solcoo.merchant.R;
import com.solcoo.merchant.base.BaseActivity;
import com.solcoo.merchant.base.task.TaskHelper;
import com.solcoo.merchant.base.task.TaskHelper.Callback;
import com.solcoo.merchant.manager.UserManager;
import com.solcoo.merchant.model.User;
import com.solcoo.merchant.ui.qrcode.QrcodeActivity;
import com.solcoo.merchant.util.DialogUtil;
import com.solcoo.merchant.util.ViewUtil;

public class SettingActivity extends BaseActivity {

	private static final String TMP_HEAD_PIC_NAME = "head_pic.jpg"; // 头像在本地默认存储文件名

	private String mCacheDir = null;

	private ImageView headPic;

	private TextView cardNo;

	private TextView sex;

	private TextView nick;

	private Dialog logoutDialog;

	private Dialog successDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setting);
		logoutDialog = DialogUtil.createDialog(this, logoutOnClickListener,
				null, null, "确定要退出登录", null);
		successDialog = DialogUtil.createDialog(this, null, null, null,
				"修改头像成功", null);
		headPic = (ImageView) findViewById(R.id.userHeadPic);
		cardNo = (TextView) findViewById(R.id.card_no);
		sex = (TextView) findViewById(R.id.sex);
		nick = (TextView) findViewById(R.id.nick);
		findViewById(R.id.head_pic_layout).setOnClickListener(
				onHeadPicClickListener);
	}

	@Override
	protected void onResume() {
		super.onResume();
		cardNo.setText(String.valueOf(ApplicationExt.getUser().yonghum));
		sex.setText(ApplicationExt.getUser().getSexName());
		nick.setText(ApplicationExt.getUser().nicheng);
		ImageLoader.getInstance().load(ApplicationExt.getUser().touxiang,
				headPic);

	}

	private View.OnClickListener onHeadPicClickListener = new View.OnClickListener() {
		BottomDialog dialog;

		@Override
		public void onClick(View v) {
			// 日志埋点
			if (dialog == null) {
				String[] buttonNames = new String[] { "拍照", "相册" };
				dialog = new BottomDialog(v.getContext(), buttonNames,
						new OnClickListener[] { onCameraClickListener,
								onAlbumnClickListener });
			}
			dialog.show();
		}

		private OnClickListener onAlbumnClickListener = new OnClickListener() {

			public void onClick(View v) {
				dialog.dismiss();
				Intent intent = new Intent(Intent.ACTION_PICK, null);
				if (App.isIntentAvailable(intent)) {
					intent.setDataAndType(
							MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
							"image/*");
					startActivityForResult(
							Intent.createChooser(intent, "选择相册"),
							BitmapHelper.REQUEST_CODE_ALBUMN);
				} else {
					DialogUtil.createDialog(v.getContext(), null, null, null,
							"未找到你的相册", null);
				}
			}
		};

		private OnClickListener onCameraClickListener = new OnClickListener() {
			public void onClick(View v) {
				// 日志埋点
				dialog.dismiss();
				mCacheDir = FileUtil.getSdDirPath();
				File temp = new File(mCacheDir, TMP_HEAD_PIC_NAME);
				if (temp.exists()) {
					temp.delete(); // 每次点击拍照自动将之前的文件删除
				}
				if (BitmapHelper.checkCameraHardware()
						&& BitmapHelper.checkExternalStorageState()) {
					Intent intent = new Intent(v.getContext(),
							CameraActivity.class);
					intent.putExtra("dir", mCacheDir);
					intent.putExtra("fileName", TMP_HEAD_PIC_NAME);
					startActivityForResult(intent,
							BitmapHelper.REQUEST_CODE_CAMERA);
				}
			}
		};
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		if (resultCode != RESULT_OK)
			return;
		switch (requestCode) {
		// 如果是直接从相册获取
		case BitmapHelper.REQUEST_CODE_ALBUMN:
			if (intent != null) {
				startPhotoZoom(intent.getData());
			}
			break;
		// 如果是调用相机拍照时
		case BitmapHelper.REQUEST_CODE_CAMERA:
			File temp = new File(mCacheDir, TMP_HEAD_PIC_NAME);
			if (temp.exists()) { // 当有图片时才进行裁剪
				startPhotoZoom(Uri.fromFile(temp));
			}
			break;
		// 取得裁剪后的图片
		case BitmapHelper.REQUEST_CODE_CUT:
			if (intent != null) {
				String url = intent.getStringExtra(CropActivity.OUTPUT_URL);
				ImageLoader.getInstance().load(url, headPic,
						RoundedCornerConvertor.getInstance());
				uploadPic(url);
			}
			break;
		default:
			break;

		}
		super.onActivityResult(requestCode, resultCode, intent);
	}

	private Callback<User> editCallback = new Callback<User>() {

		@Override
		public void onSuccess(User result) {
			UserManager.getInstance().setUser(result);
			successDialog.show();
		}

		@Override
		public void onFail(User result) {
			ViewUtil.showToast(SettingActivity.this, result.failMsg);
		}
	};

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {
		File file;
		if (uri.getScheme().equalsIgnoreCase("file")) { // 从拍照而来
			file = new File(uri.getPath());
		} else { // 从相册而来,content
			file = BitmapHelper.getFileByUri(uri);
		}
		BitmapHelper.startPhotoCrop(file.getAbsolutePath(),
				FileUtil.getImageCacheDir() + "/userHeadPic.jpg", this, 0.5f,
				120, 120);
	}

	public void logoutOnClick(View v) {
		logoutDialog.show();
	}

	public void editInfoOnClick(View v) {
		Intent it = new Intent();
		switch (v.getId()) {
		case R.id.nick_layout:
			it.setClass(v.getContext(), EditInputActivity.class);
			it.putExtra(EditBaseActivity.EDIT_NAME, "昵称");
			it.putExtra(EditBaseActivity.EDIT_KEY, "nicheng");
			it.putExtra(EditBaseActivity.EDIT_OLD_VALUE,
					ApplicationExt.getUser().nicheng);
			break;
		case R.id.sex_layout:
			it.setClass(v.getContext(), EditSexActivity.class);
			it.putExtra(EditBaseActivity.EDIT_NAME, "性别");
			it.putExtra(EditBaseActivity.EDIT_KEY, "xingbie");

			it.putExtra(EditBaseActivity.EDIT_OLD_VALUE,
					String.valueOf(ApplicationExt.getUser().xingbie));
			break;
		case R.id.qrcode_layout:
			it.setClass(v.getContext(), QrcodeActivity.class);
			break;
		}
		v.getContext().startActivity(it);
	}

	private DialogInterface.OnClickListener logoutOnClickListener = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			UserManager.getInstance().logout(SettingActivity.this);
		}
	};

	private void uploadPic(String url) {
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("touxiang", new File(url));
		params.put("yonghum", ApplicationExt.getUser().yonghum);
		TaskHelper.oper(this, Constant.URL.getHeadEdit(), editCallback,
				User.class, params);
	}

}
